package cc.fs.zhihuapp.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by fostion on 2015/9/22.
 * 基本Android数据库操作
 */
public class DatabaseHelper {

    private Context context;
    private SQLiteDatabase database;


    public DatabaseHelper(Context context){
        this.context = context;
        initDatabase();
    }

    private void initDatabase(){
        database = context.openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);

        if(!isTabExist("user_info")){
            database.execSQL("create table user_info(id INTEGER PRIMARY KEY, name TEXT NOT NULL, " +
                    "avatar_url TEXT NOT NULL)");
        }
    }

    public void release() {
        database.close();
    }

    public synchronized void saveUser(String id,String name,String avatar){
        Cursor c = database.rawQuery("select * from user_info where id=" + id, null);

        ContentValues valuesUser = new ContentValues();
        valuesUser.put("id", id);
        valuesUser.put("name", name);
        valuesUser.put("avatar_url", avatar);

        if (c.getCount() == 0) {
            database.insert("user_info", "id", valuesUser);
        } else {
            database.update("user_info", valuesUser, "id=" + id, null);
        }
        c.close();
    }



    public synchronized String getUser(String id){
        String name = "";
        String avatar = "";
        Cursor c = database.rawQuery("select * from user_info where id=" + id, null);
        if (c.getCount() != 0) {
            c.moveToFirst();

            int index1 = c.getColumnIndex("name");
            int index2 = c.getColumnIndex("avatar_url");

            name = c.getString(index1);
            avatar = c.getString(index2);
        }
        c.close();
        return name;
    }

    public synchronized void deleteUser(String id){

    }



    public boolean isTabExist(String tabName) {
        boolean result = false;
        if (tabName == null) {
            return false;
        }
        Cursor cursor = null;
        try {
            String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"
                    + tabName.trim() + "' ";
            cursor = database.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    result = true;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
